<script setup lang="ts">
import axios from 'axios';
import { watch, ref } from 'vue';
import { ArticleResData, ArticleItem } from '../types/data';

// 从父组件获取的当前频道id
const props = defineProps<{
  channelId: number
}>()

// 准备数组接收数据
const articleList = ref<ArticleItem[]>([])

// 监听外面传入的频道id变化
watch(
  () => props.channelId,
  // 一旦变化重新获取数据
  async() => {
    const res = await axios<ArticleResData>({
      url: `http://geek.itheima.net/v1_0/articles`,
      params: {
          channel_id: props.channelId,
          timestamp: Date.now(),
      },
    })
    articleList.value = res.data.data.results
  },
  // 哪怕不变化, 进来时也是要用默认的id先取一次数据
  {
    immediate: true
  }
)


</script>

<template>
  <div class="article-list">
    <div class="article-item" v-for="item in articleList" :key="item.art_id">
      <p class="title">{{ item.title }}</p>
      <img
        v-for="(src, i) in item.cover.images"
        :key="i"
        class="img"
        :src="src"
        alt=""
      />
      <div class="info">
        <span>{{ item.aut_name }}</span>
        <span>{{ item.comm_count }}评论</span>
        <span>{{ item.pubdate }}</span>
      </div>
    </div>
  </div>
</template>